﻿using Gobang.ToolClass.Model;
using System.Net;

namespace Gobang.ToolClass.Networking
{
    public static class SendEx
    {
        /// <summary>
        /// 获取值类型的字节大小。
        /// </summary>
        const int BYTESIZE = sizeof(byte);
        /// <summary>
        /// 发送字节（支持大文件）
        /// </summary>
        /// <param name="client">网络客户端</param>
        /// <param name="msgMerge">消息模型</param>
        /// <param name="iPEndPoint">IP端点</param>
        public static void Send(this IClientNetworking client, MsgMergeModel msgMerge, IPEndPoint iPEndPoint)
        {
            msgMerge.MsgId = Guid.NewGuid().ToString();
            byte[] data = msgMerge.GetBytes();
            int dataLen = data.Length;
            int sendLen = 1024;
            if (dataLen > sendLen)
            {
                data = null;
                data = msgMerge.GetBytes();
                dataLen = data.Length;
                int targetLen = sendLen;
                int desSize = sendLen * BYTESIZE;
                int srcOffset = 0;
                while (dataLen > 0)
                {
                    if (dataLen < sendLen)
                    {
                        targetLen = dataLen;
                        desSize = targetLen * BYTESIZE;
                    }
                    byte[] buffer = new byte[targetLen];
                    Buffer.BlockCopy(data, srcOffset, buffer, 0, desSize);
                    client.Send(iPEndPoint, buffer);
                    buffer = null;
                    dataLen -= sendLen;
                    srcOffset += desSize;
                }
            }
            else
            {
                client.Send(iPEndPoint, data);
            }
        }
    }
}
